package com.dabai.wifiseepass.activitys;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;

import android.Manifest;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSON;
import com.dabai.wifiseepass.MainActivity;
import com.dabai.wifiseepass.R;
import com.dabai.wifiseepass.utils.Base64;
import com.dabai.wifiseepass.utils.DabaiUtils;
import com.dabai.wifiseepass.utils.DateUtils;
import com.dabai.wifiseepass.utils.WifiManage;
import com.google.android.material.textfield.TextInputLayout;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.util.Hashtable;
import java.util.List;

public class CreateActivity extends AppCompatActivity {
    Context context;

    TextInputLayout til1, til2;
    EditText et1, et2;

    TextView tv1, tv2;
    ImageView iv1;

    CardView card1;
    private int checkResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create);

        context = getApplicationContext();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);


        til1 = findViewById(R.id.til1);
        til2 = findViewById(R.id.til2);
        et1 = findViewById(R.id.ed1);
        et2 = findViewById(R.id.ed2);
        tv1 = findViewById(R.id.textView5);
        tv2 = findViewById(R.id.textView6);
        iv1 = findViewById(R.id.imageView5);
        card1 = findViewById(R.id.card1);


        if (jianchadingwei()) {
            try {
                WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();

                et1.setText(wifiInfo.getSSID().replace("\"", ""));
                changeQr();
            }catch (Exception e){}
        }


        et1.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                changeQr();
            }
        });

        et2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                changeQr();
            }
        });

    }



    //根据view获取bitmap
    public static Bitmap getBitmapByView(View view) {
        int h = 0;
        Bitmap bitmap = null;
        bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),
                Bitmap.Config.RGB_565);
        final Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
        return bitmap;
    }



    public void changeQr() {

        String wifi = til1.getEditText().getText().toString();
        String pass = til2.getEditText().getText().toString();


        String text;

        if (pass.equals("")) {
            text = "WIFI:T:;P:;S:" + wifi + ";";
        } else {
            text = "WIFI:T:WPA;P:" + pass + ";S:" + wifi + ";";
        }

        ToRes(text, wifi, pass);

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case android.R.id.home:
                // 处理返回逻辑
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }


    private void ToRes(String text, final String name, final String pass) {


        if (!name.equals("")) {
            tv1.setText("名称:" + name);
        } else {
            tv1.setText("名称:" + "无名称");
        }

        if (!pass.equals("")) {
            tv2.setText("密码:" + pass);
        } else {
            tv2.setText("密码:" + "无密码");
        }


        if (name.equals("") || (pass.length() < 8 && pass.length() != 0)) {

            //xxxxxxx
            Bitmap bit = createQRCodeBitmap("无效的WiFi信息码！", 700, 700, "UTF-8", "H", "1", Color.BLACK, Color.WHITE);
            iv1.setImageBitmap(bit);

        } else {
            //生成二维码设置到 img1
            Bitmap bit = createQRCodeBitmap(text, 700, 700, "UTF-8", "H", "1", Color.BLACK, Color.WHITE);
            iv1.setImageBitmap(bit);
        }
    }

    //检查定位权限
    private boolean jianchadingwei() {
        checkResult = context.checkCallingOrSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
        //if(!=允许),抛出异常
        if (checkResult != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1); // 动态申请读取权限
            Toast.makeText(context, "缺少必要的定位权限！", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }


    /**
     * 生成简单二维码
     *
     * @param content                字符串内容
     * @param width                  二维码宽度
     * @param height                 二维码高度
     * @param character_set          编码方式（一般使用UTF-8）
     * @param error_correction_level 容错率 L：7% M：15% Q：25% H：35%
     * @param margin                 空白边距（二维码与边框的空白区域）
     * @param color_black            黑色色块
     * @param color_white            白色色块
     * @return BitMap
     */
    public static Bitmap createQRCodeBitmap(String content, int width, int height,
                                            String character_set, String error_correction_level,
                                            String margin, int color_black, int color_white) {
        // 字符串内容判空
        if (TextUtils.isEmpty(content)) {
            return null;
        }
        // 宽和高>=0
        if (width < 0 || height < 0) {
            return null;
        }
        try {
            /** 1.设置二维码相关配置 */
            Hashtable<EncodeHintType, String> hints = new Hashtable<>();
            // 字符转码格式设置
            if (!TextUtils.isEmpty(character_set)) {
                hints.put(EncodeHintType.CHARACTER_SET, character_set);
            }
            // 容错率设置
            if (!TextUtils.isEmpty(error_correction_level)) {
                hints.put(EncodeHintType.ERROR_CORRECTION, error_correction_level);
            }
            // 空白边距设置
            if (!TextUtils.isEmpty(margin)) {
                hints.put(EncodeHintType.MARGIN, margin);
            }
            /** 2.将配置参数传入到QRCodeWriter的encode方法生成BitMatrix(位矩阵)对象 */
            BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);

            /** 3.创建像素数组,并根据BitMatrix(位矩阵)对象为数组元素赋颜色值 */
            int[] pixels = new int[width * height];

            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    //bitMatrix.get(x,y)方法返回true是黑色色块，false是白色色块
                    if (bitMatrix.get(x, y)) {
                        pixels[y * width + x] = color_black;//黑色色块像素设置
                    } else {
                        pixels[y * width + x] = color_white;// 白色色块像素设置
                    }
                }
            }
            /** 4.创建Bitmap对象,根据像素数组设置Bitmap每个像素点的颜色值,并返回Bitmap对象 */
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
            return bitmap;
        } catch (WriterException e) {
            return null;
        }
    }

    public void SaveImg(View view) {

        photoBitmap = getBitmapByView(card1);

        /**
         * SAF框架写入文件
         */
        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
        // 只显示可以打开的文件
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/jpeg");
        intent.putExtra(Intent.EXTRA_TITLE, "WiFi码_" + et1.getText().toString() + "");
        startActivityForResult(intent, 201);

    }

    Bitmap photoBitmap;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        Uri uri = null;

        if (resultCode == Activity.RESULT_OK) {

            if (requestCode == 201) {

                if (data != null) {
                    uri = data.getData();
                }
                if (uri != null) {
                    try {

                        FileOutputStream fileOutputStream = null;
                        try {
                            // 获取 OutputStream
                            fileOutputStream = (FileOutputStream) getContentResolver().openOutputStream(uri);

                            if (photoBitmap != null) {
                                if (photoBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream)) {
                                    fileOutputStream.flush();
                                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                                    Toast.makeText(context, "保存成功！", Toast.LENGTH_SHORT).show();

                                }
                            }
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                            try {
                                fileOutputStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }

                    } catch (Exception e) {
                        Toast.makeText(context, "导出失败!", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
        }

    public void CopyInfo(View view) {

        String wifi = til1.getEditText().getText().toString();
        String pass = til2.getEditText().getText().toString();

        if (wifi.isEmpty()) {
            Toast.makeText(context, "SSID为空！", Toast.LENGTH_SHORT).show();
            return;
        }

        ClipboardManager clipboardManager = (ClipboardManager) getApplicationContext().getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData mclipData = ClipData.newPlainText("Label", onePeizhima(wifi, pass));
        clipboardManager.setPrimaryClip(mclipData);

        Toast.makeText(this, "复制完成", Toast.LENGTH_SHORT).show();

    }


    String info = "";

    /**
     * 生成单个WiFi base64配置码
     */
    private String onePeizhima(String ssid, String pass) {

        String str = "[{\"password\":\"" + (pass.equals("") ? "无密码" : pass) + "\",\"ssid\":\"" + ssid + "\"}]";

        Base64 base = new Base64();
        String wifisbase = base.encode(str);

        return wifisbase;
    }



}